package com.ruoyi.mateCheck.service.impl;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.mateCheck.domain.MateCheck;
import com.ruoyi.mateCheck.domain.MateCheckModel;
import com.ruoyi.mateCheck.domain.MateCheckProduct;
import com.ruoyi.mateCheck.domain.MateCheckResult;
import com.ruoyi.mateCheck.domain.MateCheckSample;
import com.ruoyi.mateCheck.domain.MateTest;
import com.ruoyi.mateCheck.domain.MateUserDevice;
import com.ruoyi.mateCheck.mapper.MateCheckMapper;
import com.ruoyi.mateCheck.mapper.MateTestMapper;
import com.ruoyi.mateCheck.service.MateCheckService;
import com.ruoyi.mateDevice.domain.MateDevice;
import com.ruoyi.mateDevice.mapper.MateDeviceMapper;
import com.ruoyi.mateInventory.domain.MateInventoryModel;
import com.ruoyi.mateInventory.mapper.MateInventoryMapper;
import com.ruoyi.material.domain.MateProductCheck;
import com.ruoyi.productCheck.domain.CheckInformationModel;
import com.ruoyi.productCheck.domain.CheckSample;
import com.ruoyi.readyProcurement.domain.ReadyProcurement;
import com.ruoyi.readyProcurement.mapper.ReadyMapper;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @Author
 * @Version 1.0
 */
@Service
public class MateCheckServiceImpl implements MateCheckService {

    @Autowired
    MateCheckMapper mateCheckMapper;

    @Autowired
    ReadyMapper readyMapper;

    @Autowired
    MateTestMapper mateTestMapper;

    @Autowired
    MateDeviceMapper mateDeviceMapper;

    @Override
    public int addCheckInformation(MateCheck mateCheckInformation) {
        mateCheckInformation.setDeptId(SecurityUtils.getDeptId());
        int a = 0;
        mateCheckInformation.setInformationList(mateCheckInformation.getOtherInformation().toString());
        if (mateCheckInformation.getMateChcekModels() != null && mateCheckInformation.getMateCheckResults() != null && mateCheckInformation.getMateCheckProducts() != null) {
            try {
                MateTest mateTest = new MateTest();
                MateUserDevice mateUserDevice = new MateUserDevice();
                a = mateCheckMapper.addCheckInformation(mateCheckInformation);
                ReadyProcurement readyProcurement = new ReadyProcurement();
                readyProcurement.setReadyId(mateCheckInformation.getReadyId());
                readyProcurement.setIsCreatCheck("1");
                readyMapper.updateReadyProcurement(readyProcurement);

                for (MateCheckModel mateCheckModel : mateCheckInformation.getMateChcekModels()) {
                    mateCheckModel.setDeptId(SecurityUtils.getDeptId());
                    mateCheckModel.setCkInformationId(mateCheckInformation.getCkInformationId());
                    mateUserDevice.setDeptId(SecurityUtils.getDeptId());
                    mateUserDevice.setCkInformationId(mateCheckInformation.getCkInformationId());
                    mateUserDevice.setDeviceName(mateCheckModel.getDeviceName());
                    mateUserDevice.setMtdeviceId(mateCheckModel.getMtdeviceId());
                    mateUserDevice.setMateproductId(mateCheckModel.getMateproductId());
                    mateUserDevice.setDeviceStatus("正常");

                    mateDeviceMapper.insertUserDevice(mateUserDevice);
                    mateCheckMapper.insertCheckModel(mateCheckModel);

                }
                for (MateCheckResult mateCheckResult : mateCheckInformation.getMateCheckResults()) {
                    mateCheckResult.setDeptId(SecurityUtils.getDeptId());
                    mateCheckResult.setCkInformationId(mateCheckInformation.getCkInformationId());
                    mateTest.setDeptId(SecurityUtils.getDeptId());
                    mateTest.setCkInformationId(mateCheckInformation.getCkInformationId());
                    mateTest.setCheckProject(mateCheckResult.getCheckProject());
                    mateTest.setCheckFlow(mateCheckResult.getCheckFlow());
                    mateTest.setCheckResult(mateCheckResult.getCheckResult());
                    mateTest.setCheckIstrue(mateCheckResult.getCheckAward());
                    mateTest.setSampleNum(mateCheckResult.getSampleNum());
                    mateCheckMapper.insertCheckResult(mateCheckResult);
                    mateTestMapper.insertTestRecord(mateTest);
                }
                for (MateCheckProduct mateCheckProduct : mateCheckInformation.getMateCheckProducts()) {
                    mateCheckProduct.setDeptId(SecurityUtils.getDeptId());
                    mateCheckProduct.setCkInformationId(mateCheckInformation.getCkInformationId());
                    mateCheckMapper.insertCheckProduct(mateCheckProduct);
                }

            } catch (Exception e) {
                a = 0;
                mateCheckMapper.deleteMateCheck(mateCheckInformation.getCkInformationId());
                mateCheckMapper.deleteMateCheckModelById(mateCheckInformation.getCkInformationId());
                mateCheckMapper.removeCheckResult(mateCheckInformation.getCkInformationId());
                mateCheckMapper.removeCheckProduct(mateCheckInformation.getCkInformationId());
                mateTestMapper.removeTestRecord(mateCheckInformation.getCkInformationId());
                mateDeviceMapper.deleteUserDevice(mateCheckInformation.getCkInformationId());
            }
        }
        return a;

    }

    @Override
    public List<MateCheck> selectCheckInformation(MateCheck mateCheckInformation) {
        return mateCheckMapper.selectCheckInformation(mateCheckInformation);
    }

    @Override
    public int updateCheckInformation(MateCheck mateCheck) {
        MateTest mateTest = new MateTest();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Long ckInformationId = mateCheck.getCkInformationId();
        mateCheck.setDeptId(SecurityUtils.getDeptId());
        List<Long> longs = mateCheckMapper.selectMateCheckModel(ckInformationId);
        List<Long> longs1 = new ArrayList<>();
        if (mateCheck.getMateCheckProducts() != null && mateCheck.getMateChcekModels() != null && mateCheck.getMateCheckResults() != null) {
            for (int i = 0; i < mateCheck.getMateChcekModels().size(); i++) {
                mateCheck.getMateChcekModels().get(i).setCheckNo(null);
                mateCheck.getMateChcekModels().get(i).setCkInformationId(mateCheck.getCkInformationId());
            }
            for (int i = 0; i < longs.size(); i++) {
                longs1.add(longs.get(i));
            }
            for (MateCheckModel mateCheckModel : mateCheck.getMateChcekModels()) {
                if (mateCheckModel.getCheckNo() != null) {
                    Long checkNo = mateCheckModel.getCheckNo();
                    longs1.add(checkNo);
                    mateCheckMapper.updateCheckModel(mateCheckModel);
                } else {
                    mateCheckModel.setCkInformationId(mateCheck.getCkInformationId());
                    mateCheckModel.setDeptId(sysUser.getDeptId());
                    mateCheckMapper.insertCheckModel(mateCheckModel);
                }

            }
            if (longs1.size() != 0 && longs1 != null) {
                for (int i = 0; i < longs.size(); i++) {
                    mateCheckMapper.deleteMateCheckModel(longs.get(i));
                }
            }
            mateCheckMapper.removeCheckResult(mateCheck.getCkInformationId());
            mateTestMapper.removeTestRecord(mateCheck.getCkInformationId());
            for (MateCheckResult mateCheckResult : mateCheck.getMateCheckResults()) {
                mateCheckResult.setCkInformationId(mateCheck.getCkInformationId());
                mateCheckResult.setDeptId(sysUser.getDeptId());
                mateCheckMapper.insertCheckResult(mateCheckResult);
                mateTest.setDeptId(SecurityUtils.getDeptId());
                mateTest.setCkInformationId(mateCheck.getCkInformationId());
                mateTest.setCheckProject(mateCheckResult.getCheckProject());
                mateTest.setCheckFlow(mateCheckResult.getCheckFlow());
                mateTest.setCheckResult(mateCheckResult.getCheckResult());
                mateTest.setCheckIstrue(mateCheckResult.getCheckAward());
                mateTest.setSampleNum(mateCheckResult.getSampleNum());

                mateTestMapper.insertTestRecord(mateTest);

            }
            mateCheckMapper.removeCheckProduct(mateCheck.getCkInformationId());
            for (MateCheckProduct mateCheckProduct : mateCheck.getMateCheckProducts()) {
                mateCheckProduct.setDeptId(SecurityUtils.getDeptId());
                mateCheckProduct.setCkInformationId(mateCheck.getCkInformationId());
                mateCheckMapper.insertCheckProduct(mateCheckProduct);

            }
        } else {
            if (longs != null) {
                for (int i = 0; i < longs.size(); i++) {
                    mateCheckMapper.deleteMateCheckModel(longs.get(i));
                }
            }
            mateCheckMapper.removeCheckResult(mateCheck.getCkInformationId());
            mateCheckMapper.removeCheckProduct(mateCheck.getCkInformationId());
        }
        mateCheck.setInformationList(mateCheck.getOtherInformation().toString());
        int a = mateCheckMapper.updateCheckInformation(mateCheck);
        return a;
    }

    @Override
    public MateCheck selectCheckInformationById(Long ckInformationId) {
        return mateCheckMapper.selectCheckInformationById(ckInformationId);
    }


    @Override
    public List<MateCheck> selectMateProductCheck(Long deptId) {
        return mateCheckMapper.selectMateProductCheck(deptId);
    }

    @Override
    public String createWord(Long ckInformationId) {

        int num = 0;
        try {
            XWPFDocument document = new XWPFDocument();
            List<MateCheckSample> list = mateCheckMapper.selectMateCheckSample(ckInformationId);
            List<MateCheckResult> parameters = mateCheckMapper.selectMateCheckResult(ckInformationId);

            XWPFParagraph paragraph = document.createParagraph();
            paragraph.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun run = paragraph.createRun();
            run.setText("附件：原材料检验结果");
            run.setFontSize(16);
            run.setBold(true);
            run.addBreak();

            // 创建一个表格
            XWPFTable table = document.createTable(list.size() + 2, parameters.size() + 2); // 调整行数加1
            CTTblPr tblPr = table.getCTTbl().addNewTblPr();

            tblPr.addNewTblW().setW(BigInteger.valueOf(8000)); // 设置表格宽度
            for (int i = 0; i < list.size() + 2; i++) { // 调整循环次数
                XWPFTableRow row = table.getRow(i);
                row.setHeight(500); // 设置行高
                for (int j = 0; j < parameters.size() + 2; j++) {
                    XWPFTableCell cell = row.getCell(j);
                    cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 垂直居中对齐
                    cell.setWidth("4000"); // 设置列宽
                }
            }

            XWPFTableCell cellHeader = table.getRow(0).getCell(0);
            cellHeader.setText("样本");
            cellHeader.getParagraphArray(0).setAlignment(ParagraphAlignment.CENTER);
            cellHeader.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);

            XWPFTableCell cellSecondRow = table.getRow(1).getCell(0);
            cellSecondRow.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);

            // 填充第一列除第一行
            for (int i = 2; i < list.size() + 2; i++) {
                XWPFTableCell cell = table.getRow(i).getCell(0);
                cell.setText(list.get(i - 2).getSampleName());

                CTP ctp = cell.getCTTc().getPList().get(0);
                CTPPr ctpPr = ctp.getPPr();
                if (ctpPr == null) {
                    ctpPr = ctp.addNewPPr();
                }
                CTJc jc = ctpPr.getJc();
                if (jc == null) {
                    jc = ctpPr.addNewJc();
                }
                jc.setVal(STJc.CENTER);
            }

            // 填充第一行除第一列的数据
            for (int j = 1; j < parameters.size() + 1; j++) {
                XWPFTableCell cell = table.getRow(0).getCell(j);
                cell.setText(parameters.get(j - 1).getCheckProject());

                CTP ctp = cell.getCTTc().getPList().get(0);
                CTPPr ctpPr = ctp.getPPr();
                if (ctpPr == null) {
                    ctpPr = ctp.addNewPPr();
                }
                CTJc jc = ctpPr.getJc();
                if (jc == null) {
                    jc = ctpPr.addNewJc();
                }
                jc.setVal(STJc.CENTER);

            }

            for (int j = 1; j < parameters.size() + 1; j++) {
                XWPFTableCell cell = table.getRow(1).getCell(j);
                cell.setText(parameters.get(j - 1).getCheckFlow());

                CTP ctp = cell.getCTTc().getPList().get(0);
                CTPPr ctpPr = ctp.getPPr();
                if (ctpPr == null) {
                    ctpPr = ctp.addNewPPr();
                }
                CTJc jc = ctpPr.getJc();
                if (jc == null) {
                    jc = ctpPr.addNewJc();
                }
                jc.setVal(STJc.CENTER);
            }

            // 填充除第一行第一列外的数据
            for (int i = 2; i < list.size() + 2; i++) { // 修改起始行数
                for (int j = 1; j < parameters.size() + 1; j++) {
                    XWPFTableCell cellData = table.getRow(i).getCell(j);
                    cellData.setText(parameters.get(j - 1).getCheckResult());

                    CTP ctp = cellData.getCTTc().getPList().get(0);
                    CTPPr ctpPr = ctp.getPPr();
                    if (ctpPr == null) {
                        ctpPr = ctp.addNewPPr();
                    }
                    CTJc jc = ctpPr.getJc();
                    if (jc == null) {
                        jc = ctpPr.addNewJc();
                    }
                    jc.setVal(STJc.CENTER);

                }
            }

            for (int i = 0; i < list.size() + 2; i++) { // 修改循环次数
                XWPFTableCell cellDecide = table.getRow(i).getCell(parameters.size() + 1);
                if (i == 0) {
                    cellDecide.setText("判定");
                    cellDecide.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                    XWPFTableCell cellDecide1 = table.getRow(1).getCell(parameters.size() + 1);
                    cellDecide1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                    cellDecide.getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER); // 判定表头居中对齐

                } else {
                    cellDecide.setText(parameters.get(i - 1 < parameters.size() ? i - 1 : parameters.size() - 1).getCheckAward());
                    cellDecide.getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER); // 内容居中对齐
                }
            }
            // 保存文档
            String filePath = "D:\\ruoyi\\uploadPath\\download\\productionWord\\原材料检验结果" + ".docx";
            FileOutputStream out = new FileOutputStream(filePath);
            document.write(out);
            out.close();
            System.out.println("Word 表格创建成功！");
        } catch (Exception e) {
            e.printStackTrace();
            num = 1;
        }
        if (num == 1) {
            return "生成失败";
        } else {
            return "/productionWord/原材料检验结果.docx";
        }


    }


}

